
var key = "tk1678";
var base_url = "http://www.abbreviations.com/services/v1/defs.aspx";
var word = "";

var def_title_beg = "<h4 class=\"page_title\">";
var def_title_end = "</h4>";
var def_div = "<div class=\"hr dotted clearfix\">&nbsp;</div>";
var def_beg = "<p>";
var def_end = "</p>";
var page_content = "";

function render(result) {
	page_content = "";
	var r = result.getElementsByTagName("result");
	if(r.length == 0)
	{
		page_content = def_title_beg + "No results" + def_title_end;
		page_content += def_div;
		page_content += def_beg + "No results" + def_end;
	}
	else
	{
		for(i=0; i < r.length; i++)
		{
			page_content += def_title_beg + r[i].getElementsByTagName("term")[0].childNodes[0].nodeValue + def_title_end;
			page_content += def_div;
			page_content += def_beg + r[i].getElementsByTagName("definition")[0].childNodes[0].nodeValue + def_end;
		}
	}

	document.getElementById("content").innerHTML=page_content;
}

function displayAbout()
{
	page_content = def_title_beg + "DefinePlug" + def_title_end;
	page_content += def_div;
	page_content += def_beg + "A tool to help you <u>quickly find the meaning</u> of a word or phrase." + def_end;
	page_content += def_beg + "How often have you come across a word or phrase that you don't understand? And how often have you just ignored it? Now it is very easy to find out its meaning with just one click. Just select the word/phrase and click this button. The meaning will be displayed in this little popup. No need to open a new tab or window!" + def_end;
	document.getElementById("content").innerHTML=page_content;
}

function getSelectedWord() {
	// Send a request to fetch data from Twitter's API to the background page.
	// Specify that onText should be called with the result.
	//chrome.extension.sendRequest({'action' : 'getSelectedWord'}, onGotSelection);

	chrome.tabs.getSelected(null, function(tab) {
			chrome.tabs.sendRequest(tab.id, {'action' : 'getSelectedWord'}, onGotSelection);
			});

}

function onGotSelection(selection) {
	if(selection != null && selection != "")
	{
		word = selection;
		getDefinition();
	}
	else
	{
		displayAbout();
	}
}

function getDefinition() {
	var url = base_url + "?tokenid=" + key + "&word=" + word;
	var xmlReq = new XMLHttpRequest();
	xmlReq.onreadystatechange=function()
	{
		if (xmlReq.readyState==4 && xmlReq.status==200)
		{
			var xmlDoc=xmlReq.responseXML;
			render(xmlDoc);
		}
	}

	xmlReq.open("GET", url, true);
	xmlReq.send();
}

function fetchDefinition() {
	chrome.tabs.getSelected(null, function (tab) {
				if(tab.url.substring(0,9) == "chrome://") {
					displayAbout();
				} else {
					getSelectedWord();
				}
			});
}

